import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 使用CAS模拟实现自旋锁。
 * @author ybzou
 */
public class SpinLockDemo {
    AtomicReference<Thread> atomicReference=new AtomicReference<Thread>();

    public void lock(){
        Thread thread = Thread.currentThread();
        //加锁操作：预期值为null 表示当前没有锁，
        System.out.println(thread.getName()+"\t come in ...");
        while( !atomicReference.compareAndSet(null,thread) ){

        }
    }

    public void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName()+"\t end ...");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo spinLockDemo=new SpinLockDemo();

        new Thread(()->{
            spinLockDemo.lock();
            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
            spinLockDemo.unlock();
        },"A").start();

        TimeUnit.MILLISECONDS.sleep(500);

        new Thread(()->{
            spinLockDemo.lock();
            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
            spinLockDemo.unlock();
        },"B").start();
    }
}

